﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace DecodeInterface
{
    public sealed class DecodeExplorer
    {
        public static readonly int MaxBufferSize = 10;
        Queue<Bitmap> Buffer = new Queue<Bitmap>();

        Control decodeShow = null;
        public Control DecodeShow
        {
            get { return decodeShow; }
            set
            {
                if (value == null)
                {
                    if (decodeShow != null)
                    {
                        decodeShow.Paint -= new PaintEventHandler(decodeShow_Paint);
                        decodeShow = null;
                    }
                }
                else
                {
                    if (decodeShow == null)
                    {
                        decodeShow = value;
                        decodeShow.Paint += new PaintEventHandler(decodeShow_Paint);
                    }
                    else
                    {
                        decodeShow.Paint -= new PaintEventHandler(decodeShow_Paint);
                        decodeShow = value;
                    }
                }
            }
        }
        public Bitmap ImageDecode = null;

        void decodeShow_Paint(object sender, PaintEventArgs e)
        {
            if (this.ImageDecode == null) return;
            Graphics G = e.Graphics;
            lock (this.ImageDecode)
            {
                G.DrawImage(this.ImageDecode,
                    new Rectangle(new Point(), this.decodeShow.Size));
            }
        }

        public DecodeExplorer() { }

        public DecodeExplorer(Control decodeShow)
        {
            if (decodeShow != null)
            {
                this.decodeShow = decodeShow;
                this.decodeShow.Paint += new PaintEventHandler(decodeShow_Paint);
            }
        }

        public void InputImage(Bitmap image)
        {
            if (image != null
                && this.Buffer.Count < MaxBufferSize)
            {
                lock (image)
                {
                    this.Buffer.Enqueue(image);
                }
            }
        }

        public void ShowImage()
        {
            if (this.Buffer.Count == 0) return;
            if (this.ImageDecode != null)
            {
                lock (this.ImageDecode)
                {
                    this.ImageDecode.Dispose();
                    this.ImageDecode = null;
                }
            }
            this.ImageDecode = this.Buffer.Dequeue();

            if (this.decodeShow != null) this.decodeShow.Invalidate();
        }
    }
}
